package admin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/db"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminRoleDel(ctx context.Context, pb *pbAdmin.AdminRoleDelReq) (*pbAdmin.AdminRoleDelResp, error) {

	ids := []interface{}{}
	for _, id := range pb.Id {
		ids = append(ids, id)
	}

	if pb.OperaterId != 0 {
		roleIds := adminLogic.GetChildrenRoleIds(ctx, pb.OperaterId, true)
		if len(utils.ArrayDiff(ids, roleIds)) > 0 {
			return nil, businessError.ErrorInfoToRpcError(businessError.AdminDeniedOperateSelfRole)
		}
	}

	Db := database.Db.GetDefaultDb(ctx)

	has, dbErr := Db.Find("select * from admin_role_access where role_id in (?)", ids)

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	if has != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.AdminRoleHasUser)
	}

	row, _ := Db.Find("select * from admin_role where id in (?)", ids)

	if row == nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.NotFound)
	}

	rowCount, e := Db.TransactionFunc(func(Db *db.Db) (interface{}, error) {
		RoleRowCount, dbErr := Db.Delete("admin_role", map[string]interface{}{
			"id": ids,
		})

		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}

		if RoleRowCount <= 0 {
			return nil, businessError.ErrorInfoToRpcError(businessError.OperateError)
		}

		rowCount, dbErr := Db.Delete("admin_role_resource_access", map[string]interface{}{
			"role_id": ids,
		})

		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}

		if rowCount <= 0 {
			return nil, businessError.ErrorInfoToRpcError(businessError.OperateError)
		}

		return RoleRowCount, nil
	})

	if e != nil {
		return nil, e
	}

	return &pbAdmin.AdminRoleDelResp{
		RowCount: rowCount.(int64),
	}, nil
}
